package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;

import com.itheima.entity.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.Service.CategoryService;
import com.itheima.service.Service.DishFlavorService;
import com.itheima.service.Service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    // 分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dtoPage=new Page<>();
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Dish::getName,name).orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lqw);
        List<Dish> dishList=pageInfo.getRecords();
        List<DishDto> dishDtoList=new ArrayList<>();
        for (Dish dish : dishList) {
            Category category= categoryService.getById(dish.getCategoryId());
            DishDto dishDto=new DishDto();
            dishDto.setCategoryName(category.getName());
            BeanUtils.copyProperties(dish,dishDto);
            LambdaQueryWrapper<DishFlavor> dflqw=new LambdaQueryWrapper<>();
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dflqw.eq(DishFlavor::getDishId, dish.getId()));
            if (dishFlavorList!=null){
                dishDto.setFlavors(dishFlavorList);
            }
            dishDtoList.add(dishDto);
        }
        dtoPage.setRecords(dishDtoList);
        dtoPage.setTotal(pageInfo.getTotal());
//        Map map=new HashMap();
//        map.put("total",pageInfo.getTotal());
//        map.put("records",dishDtoList);
        return R.success(dtoPage);
    }
    //添加
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
//        dishMapper.insert(dishDto);
//        List<DishFlavor> flavors = dishDto.getFlavors();
//        if (flavors != null && flavors.size() != 0) {
//            for (DishFlavor flavor : flavors) {
//                flavor.setDishId(dishDto.getId());
//                dishFlavorMapper.insert(flavor);
//            }
//        }
//        Set keys=redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus());
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("添加成功");
    }
    //根据id查询
    @GetMapping("/{id}")
    public R getByid(@PathVariable long id){
        DishDto dishDto=new DishDto();
        Dish dish = dishService.getById(id);
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> dflqw=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> cglqw=new LambdaQueryWrapper<>();
        dflqw.eq(DishFlavor::getDishId,id);
        cglqw.eq(Category::getId,id);
        List<DishFlavor> dflist = dishFlavorService.list(dflqw);
        String categoryName = categoryService.getById(dish.getCategoryId()).getName();
        dishDto.setCategoryName(categoryName);
        dishDto.setFlavors(dflist);
        return R.success(dishDto);
    }
    //修改
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus());
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDto,dish);

        LambdaQueryWrapper<DishFlavor> dflqw=new LambdaQueryWrapper<>();
        dflqw.eq(DishFlavor::getDishId,dish.getId());
       dishFlavorService.remove(dflqw);
        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setDishId(dish.getId());
        }
        if (dishService.updateById(dish)&&dishFlavorService.saveBatch(dishDto.getFlavors())){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }
    //删除
    @DeleteMapping
    public R remove(@RequestParam List<Long> ids){
        dishService.removeByIds(ids);
        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> dflqw=new LambdaQueryWrapper<>();
            dflqw.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(dflqw);
        }
        return R.success("删除成功");
    }
    //起售/停售 批量起售/批量停售
    @PostMapping("/status/{status}")
    public R updatstatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);

        }
        return R.success("修改改成功");
    }
    @GetMapping("/list")
    public R<List<DishDto>> getList( Dish dish,HttpServletRequest request){
        List<DishDto> dishDtos=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtos= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos!=null){
            return R.success(dishDtos);
        }
//        log.info("---------------------------------------------------------------xx---"+name);
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        if(dish.getCategoryId()==null){
            //此时根据名字查询
            //name为null时获取session中的categoryGetId，按照id查询
            if(dish.getName()==null){
                Long categoryGetId = (Long) request.getAttribute("categoryId");
                dishQueryWrapper.eq("category_id", categoryGetId);
            }else {
                //name不为null时根据名字查询
                dishQueryWrapper.like("name",dish.getName());
            }
        }else {
            //设置session对象，此步骤在打开添加菜品后必定执行，所以一定会给session赋值
            dishQueryWrapper.eq("category_id", dish.getCategoryId());
            request.setAttribute("category_id",dish.getCategoryId());
        }

        //所有的dish菜单
        List<Dish> list = dishService.list(dishQueryWrapper);
        //新增：
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        dishDtos=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Dish dishi = list.get(i);

            //3.遍历dish中，查询对应的dish_flavor，将每条查询到的dish_flavor数组存入DishDto中
            wrapper.eq("dish_id",dishi.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(wrapper);
            dishDtos.add(i,new DishDto(dishi,flavorList));
        }
        redisTemplate.opsForValue().set(key,dishDtos,15, TimeUnit.MINUTES);
        //.返回增强类对象
        return R.success(dishDtos);
    }
}
